import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { isHttp, isEmpty } from "@/utils/validate"
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/static/images/profile.jpg'

const baseUrl = config.baseUrl

const user = {
  namespaced: true,
  state: {
    token: getToken(),
    id: storage.get(constant.id),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    phonenumber: storage.get(constant.phonenumber),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
      storage.set(constant.id, id)
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_PHONENUMBER: (state, phonenumber) => {
      state.phonenumber = phonenumber
      storage.set(constant.phonenumber, phonenumber)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          console.log('获取用户信息响应:', res)
          
          // 若依框架的用户信息通常在 res.data 中
          const user = res.data || res.user || {}
          console.log('解析的用户数据:', user)
          
          // 处理头像
          let avatar = ""
          if (user && user.avatar) {
            avatar = user.avatar
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar
            }
          } else {
            avatar = defAva
          }
          
          // 处理用户ID - 若依框架可能使用 userId 或 id
          const userid = user.userId || user.id || user.user_id || ""
          
          // 处理用户名 - 若依框架可能使用 userName、username 或 nickName
          const username = user.userName || user.username || user.nickName || user.nick_name || "用户"
          
          // 处理手机号 - 若依框架可能使用 phonenumber 或 phone
          const phonenumber = user.phonenumber || user.phone || user.mobile || ""
          
          // 处理角色和权限
          if (res.roles && res.roles.length > 0) {
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          
          // 提交到store
          commit('SET_ID', userid)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
          
          // 保存手机号到storage
          if (phonenumber) {
            commit('SET_PHONENUMBER', phonenumber)
          }
          
          console.log('用户信息已保存:', {
            userid,
            username,
            avatar,
            phonenumber
          })
          
          resolve(res)
        }).catch(error => {
          console.error('获取用户信息失败:', error)
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
